package com.raymond.httpclient;

import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

/**
 * HttpURLConnection在调用https请求前HttpsTrustManager.allowAllSSL();
 * 就可以使用https了
 * @author :  raymond
 * @version :  V1.0
 * @date :  2021-04-16 15:08
 */
public class HttpsTrustManager implements X509TrustManager {

    private static TrustManager[] trustManagers;
    private static final X509Certificate[] ACCEPTED_ISSUERS = new X509Certificate[] {};

    @Override
    public void checkClientTrusted(
            X509Certificate[] x509Certificates, String s) {
    }

    @Override
    public void checkServerTrusted(
            X509Certificate[] x509Certificates, String s) {
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return ACCEPTED_ISSUERS;
    }

    public static void allowAllSsl() {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }

        });

        SSLContext context = null;
        if (trustManagers == null) {
            trustManagers = new TrustManager[] { new HttpsTrustManager() };
        }
        try {
            context = SSLContext.getInstance("TLS");
            context.init(null, trustManagers, new SecureRandom());
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
        assert context != null;
        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    }
}
